#include "radio/sx127x_driver.h"
#include "radio/sx1276-LoRa.h"
#include "LoRa_model.h"

#define DEFAUTL_TIMEOUT 1000
static void Sx127xStartRx(lora_t *lora, uint32_t timeoutSystick);
static void SX127xSetTxPacket(lora_t *lora, void *buffer, uint16_t size, uint32_t timeoutSystick);
static void Sx127xReadRxPackage(lora_t *lora, void *buffer, uint16_t *size);
static void Sx127xStartCADCheck(lora_t *lora);

void SX1278ReadBuffer(lora_t *lora, uint8_t addr, uint8_t *buffer, uint8_t size);
void SX1278WriteBuffer(lora_t *lora, uint8_t addr, uint8_t *buffer, uint8_t size);
uint8_t u8_SFList[] = {RFLR_MODEMCONFIG2_SF_6, RFLR_MODEMCONFIG2_SF_7, RFLR_MODEMCONFIG2_SF_8, RFLR_MODEMCONFIG2_SF_9, RFLR_MODEMCONFIG2_SF_10, RFLR_MODEMCONFIG2_SF_11, RFLR_MODEMCONFIG2_SF_12};
uint8_t u8_CRList[] = {RFLR_MODEMCONFIG1_CODINGRATE_4_5, RFLR_MODEMCONFIG1_CODINGRATE_4_6, RFLR_MODEMCONFIG1_CODINGRATE_4_7, RFLR_MODEMCONFIG1_CODINGRATE_4_8};
uint8_t u8_BWList[] = {RFLR_MODEMCONFIG1_BW_7_81_KHZ, RFLR_MODEMCONFIG1_BW_10_41_KHZ, RFLR_MODEMCONFIG1_BW_15_62_KHZ, RFLR_MODEMCONFIG1_BW_20_83_KHZ, RFLR_MODEMCONFIG1_BW_31_25_KHZ, RFLR_MODEMCONFIG1_BW_41_66_KHZ, RFLR_MODEMCONFIG1_BW_62_50_KHZ, RFLR_MODEMCONFIG1_BW_125_KHZ, RFLR_MODEMCONFIG1_BW_250_KHZ, RFLR_MODEMCONFIG1_BW_500_KHZ};
uint32_t softTimeout = DEFAUTL_TIMEOUT;									  // 软件超时时间
volatile static tRFLRStates loraStatus = RFLR_STATE_IDLE;				  // 当前状态


/********************************************************
 * 功能：CI24R1 初始化
 * ******************************************************/
void nf_Setup_SX127x_noname_f(lora_t *lora,lora_msg_cb byte_cb,lora_msg_cb gpio_and_delay)
{
	lora->byte_cb=byte_cb;
	lora->gpio_and_delay_cb=gpio_and_delay;
}
/// @brief 初始化LoRa 配置
/// @param lora lora 设备句柄
/// @param stting 配置参数
void sx127xInit(lora_t *lora, lora_config_t *stting)
{
	Sx127xRestart(lora);
	while (0x6c != Read127xReg(lora,0x06))
	{
		lora->gpio_and_delay_cb(lora,LoRa_MSG_DELAY_MILLI,100,0,0);
	}

	SX127xSetLoRaMode(lora);

	if (stting->SignalBw > 9)
	{
		stting->SignalBw = 9;
	}
	if (stting->ErrorCoding > 4)
	{
		stting->ErrorCoding = 4;
	}
	if (stting->ErrorCoding < 0)
	{
		stting->ErrorCoding = 0;
	}
	if (stting->SpreadingFactor > 12)
	{
		stting->SpreadingFactor = 12;
	}
	if (stting->SpreadingFactor < 6)
	{
		stting->SpreadingFactor = 6;
	}
	if (stting->Power > 20)
	{
		stting->Power = 20;
	}

	SX127xSetFrf(lora,stting->RFFrequency); // 设置频率
	// 设置带宽，纠错编码器率
	Write127xReg(lora,REG_LR_MODEMCONFIG1, u8_BWList[stting->SignalBw] | u8_CRList[stting->ErrorCoding] | RFLR_MODEMCONFIG1_IMPLICITHEADER_OFF);
	// 设置SD，CRC，超时时间
	Write127xReg(lora,REG_LR_MODEMCONFIG2, u8_SFList[stting->SpreadingFactor - 6] | RFLR_MODEMCONFIG2_TXCONTINUOUSMODE_OFF | RFLR_MODEMCONFIG2_RXPAYLOADCRC_ON | 0x03);
	Write127xReg(lora,REG_LR_SYMBTIMEOUTLSB, 0xFF); // 设置超时时间
	Write127xReg(lora,REG_LR_MODEMCONFIG3, 0x0C);   // 设置低速率

	if (stting->Power > 17)
	{
		Write127xReg(lora,REG_LR_PACONFIG, 0x80 + stting->Power - 5); // 设置功率
		Write127xReg(lora,0x4d, 0x87);								 // 设置更大功率
	}
	else
	{
		Write127xReg(lora,REG_LR_PACONFIG, 0x80 + stting->Power - 2); // 设置功率
		Write127xReg(lora,0x4d, 0x84);								 // 关闭更大功率
	}
	Write127xReg(lora,REG_LR_OCP, 0x3B); // 过流保护
	// 设置前导码长度 REG_LR_PREAMBLEMSB
	Write127xReg(lora,REG_LR_PREAMBLEMSB, stting->PreambleLength >> 8);	   // 前导码高有效位
	Write127xReg(lora,REG_LR_PREAMBLELSB, stting->PreambleLength & 0x00ff); // 前导码低有效位
}

/// @brief Sx127 复位
/// @param lora lora 设备句柄
void Sx127xRestart(lora_t *lora)
{
	lora->gpio_and_delay_cb(lora,LoRa_MSG_GPIO_RST,0,0,0);
	lora->gpio_and_delay_cb(lora,LoRa_MSG_DELAY_MILLI,10,0,0);
	lora->gpio_and_delay_cb(lora,LoRa_MSG_GPIO_RST,1,0,0);
	lora->gpio_and_delay_cb(lora,LoRa_MSG_DELAY_MILLI,10,0,0);
	loraStatus = RFLR_STATE_IDLE;
}

/// @brief 设置为Lora模式
/// @param
void SX127xSetLoRaMode(lora_t *lora)
{
	if (0 != (Read127xReg(lora,REG_LR_OPMODE) & RFLR_OPMODE_LONGRANGEMODE_ON))
	{
		return; // 当前处于lora模式
	}
	SX127xSetOpMode(lora,LORA_OPMODE_SLEEP);
	// 设置为lora模式（只有在LoRa_sleep 模式下才能操作）
	Write127xReg(lora,REG_LR_OPMODE, Read127xReg(lora,REG_LR_OPMODE) | RFLR_OPMODE_LONGRANGEMODE_ON);
}

/// @brief 写 127x寄存器
/// @param addr 寄存器地址
/// @param data 数据
void Write127xReg(lora_t *lora, uint8_t addr, uint8_t data)
{
	SX1278WriteBuffer(lora,addr, &data, 1);
}

/// @brief 读S127x寄存器
/// @param lora lora 设备句柄
/// @param addr 寄存器地址
/// @return 寄存器值
uint8_t Read127xReg(lora_t *lora, uint8_t addr)
{
	uint8_t u8_recive;

	SX1278ReadBuffer(lora,addr, &u8_recive, 1);

	return u8_recive;
}
/// @brief 写SX127x fifo
/// @param lora lora 设备句柄
/// @param buffer 数据buffer
/// @param size 数据长度
void SX127xWriteFifo(lora_t *lora, uint8_t *buffer, uint8_t size)
{
	SX1278WriteBuffer(lora,0, buffer, size);
}
/// @brief 读 SX127x fifo
/// @param lora lora 设备句柄
/// @param buffer 数据buffer
/// @param size 数据长度
void SX127xReadFifo(lora_t *lora, uint8_t *buffer, uint8_t size)
{
	SX1278ReadBuffer(lora,0, buffer, size);
}

/// @brief 设置OpMode 模式
/// @param lora lora 设备句柄
/// @param opMode
void SX127xSetOpMode(lora_t *lora, LoRaOpModeType opMode)
{
	if (opMode == SX127xGetOpMode(lora))
	{
		return; // 当前模式正确，不用切换
	}
	Write127xReg(lora,REG_LR_OPMODE, (Read127xReg(lora,REG_LR_OPMODE) & RFLR_OPMODE_MASK) | opMode | RFLR_OPMODE_FREQMODE_ACCESS_LF);
	//lora->gpio_and_delay_cb(lora,LoRa_MSG_DELAY_MILLI,1,0,0);
}

/// @brief 获取OpModele
/// @param lora
/// @return
LoRaOpModeType SX127xGetOpMode(lora_t *lora)
{
	return (LoRaOpModeType)(Read127xReg(lora,REG_LR_OPMODE) & RFLR_OPMODE_MASK);
}

/// @brief 读sx127x 数据
/// @param lora 设备句柄
/// @param addr 地址
/// @param buffer 数据缓存
/// @param size 长度
void SX1278ReadBuffer(lora_t *lora, uint8_t addr, uint8_t *buffer, uint8_t size)
{
	uint8_t status;
	addr=addr&0x7F;
	lora->gpio_and_delay_cb(lora,LoRa_MSG_GPIO_CS,0,0,0);

	lora->byte_cb(lora,LoRa_MSG_BYTE_Transmit,1,&addr,&status);
  lora->byte_cb(lora,LoRa_MSG_BYTE_Receive,size,buffer,&status);

	lora->gpio_and_delay_cb(lora,LoRa_MSG_GPIO_CS,1,0,0);
}
/// @brief Sx127x 数据
/// @param lora lora 设备句柄
/// @param addr 地址
/// @param buffer 数据buffer
/// @param size 大小
static void SX1278WriteBuffer(lora_t *lora, uint8_t addr, uint8_t *buffer, uint8_t size)
{
	uint8_t status;
	addr=addr|0x80;
	lora->gpio_and_delay_cb(lora,LoRa_MSG_GPIO_CS,0,0,0);

	lora->byte_cb(lora,LoRa_MSG_BYTE_Transmit,1,&addr,&status);
	lora->byte_cb(lora,LoRa_MSG_BYTE_Transmit,size,buffer,&status);

	lora->gpio_and_delay_cb(lora,LoRa_MSG_GPIO_CS,1,0,0);
}
/// @brief 设置载波频率
/// @param lora lora 设备句柄
/// @param fr 频率
void SX127xSetFrf(lora_t *lora, uint32_t fr)
{
	uint8_t frfBuf[4];

	fr = fr * 0.016384; // 根据寄存器手册计算寄存器要设置的值
	mymemcpy(frfBuf, &fr, 4);
	SX127xSetOpMode(lora,LORA_OPMODE_SLEEP);

	Write127xReg(lora,REG_LR_FRFMSB, frfBuf[2]);
	Write127xReg(lora,REG_LR_FRFMID, frfBuf[1]);
	Write127xReg(lora,REG_LR_FRFLSB, frfBuf[0]);
}

/// @brief 发送数据（阻塞发送）
/// @param lora lora设备句柄
/// @param data 数据
/// @param len 数据长度
/// @param timeoutMs 超时时间
/// @return
uint8_t sx127xSend(lora_t *lora,uint32_t Fr, uint8_t *data, uint8_t len, uint32_t timeoutMs)
{
	uint16_t time=0;
	SX127xSetFrf(lora,Fr);
	Write127xReg(lora,REG_LR_PAYLOADLENGTH, len); // 设置负载长度
	Write127xReg(lora,REG_LR_FIFOTXBASEADDR, 0); // 将发送buf的基地址指向0x00，测试整个fifo都可以用来发送数据
	Write127xReg(lora,REG_LR_FIFOADDRPTR, 0);	// 将FIFO 读写指针执行0x00，此时向寄存器0x00读写数据指针会自增的将数据写入fifo
	SX127xSetOpMode(lora,LORA_OPMODE_STANDBY);	// LORA_OPMODE_SLEEP 模式不能读写fifo

	SX127xWriteFifo(lora,data, len); // 将要发送发的数据写入 fifo
	// 开启中断屏蔽位（只留下了 RFLR_IRQFLAGS_TXDONE 中断没有屏蔽掉,设置为发送模式后任意读写一个寄存器就会触发发送，这里写入这个开中断正好触发
	Write127xReg(lora,REG_LR_IRQFLAGSMASK, RFLR_IRQFLAGS_RXTIMEOUT |
										  RFLR_IRQFLAGS_RXDONE |
										  RFLR_IRQFLAGS_PAYLOADCRCERROR |
										  RFLR_IRQFLAGS_VALIDHEADER |
										  // RFLR_IRQFLAGS_TXDONE |
										  RFLR_IRQFLAGS_CADDONE |
										  RFLR_IRQFLAGS_FHSSCHANGEDCHANNEL |
										  RFLR_IRQFLAGS_CADDETECTED);
	Write127xReg(lora,REG_LR_DIOMAPPING1, (Read127xReg(lora,REG_LR_DIOMAPPING1) & RFLR_DIOMAPPING1_DIO0_MASK) | RFLR_DIOMAPPING1_DIO0_01); // DIO0����ΪTXdone�ж�
	SX127xSetOpMode(lora,LORA_OPMODE_TRANSMITTER); // 设置为发送模式
	Read127xReg(lora,REG_LR_IRQFLAGS);			  // 设置发送后读写任意寄存器可以开始发送
	if(lora->gpio_and_delay_cb(lora,LoRa_MSG_GPIO_EXIT_DIO0,timeoutMs,0,0)==0)
	{
		Write127xReg(lora,REG_LR_IRQFLAGS, RFLR_IRQFLAGS_TXDONE); // 清除中断标志位
		return 0;
	}
	return 1;
}
uint8_t sx127xStartRx(lora_t *lora,uint32_t Fr)
{
	uint16_t time=0;
	uint8_t u8_reciveLength;
  SX127xSetFrf(lora,Fr);
	SX127xSetOpMode(lora,LORA_OPMODE_STANDBY);
	Write127xReg(lora,REG_LR_FIFORXBASEADDR, 0);	   // 将接收buf的基地址指向0x00，测试整个fifo都可以用来发送数据
	Write127xReg(lora,REG_LR_FIFOADDRPTR, 0);	   // 将FIFO 读写指针执行0x00，此时向寄存器0x00读写数据指针会自增的将数据写入fifo
	Write127xReg(lora,REG_LR_SYMBTIMEOUTLSB, 0xFF); // 配置 0x1F rx 超时
	// 配置中断
	Write127xReg(lora,REG_LR_IRQFLAGSMASK, RFLR_IRQFLAGS_RXTIMEOUT |
										  // RFLR_IRQFLAGS_RXDONE |
										  //RFLR_IRQFLAGS_PAYLOADCRCERROR |
										  RFLR_IRQFLAGS_VALIDHEADER |
										  RFLR_IRQFLAGS_TXDONE |
										  RFLR_IRQFLAGS_CADDONE |
										  RFLR_IRQFLAGS_FHSSCHANGEDCHANNEL |
										  RFLR_IRQFLAGS_CADDETECTED);
	// DIO0=RxDone 0x00, DIO2=RxTimeout 0x00
	Write127xReg(lora,REG_LR_DIOMAPPING1, (Read127xReg(lora,REG_LR_DIOMAPPING1) & RFLR_DIOMAPPING1_DIO0_MASK) | RFLR_DIOMAPPING1_DIO0_00 | RFLR_DIOMAPPING1_DIO1_00);
	SX127xSetOpMode(lora,LORA_OPMODE_RECEIVER); // 连续接收
	
	// SX127xSetOpMode( LORA_OPMODE_RECIVER_SINGLE );  //单次接收
	Read127xReg(lora,REG_LR_IRQFLAGS); // 设置接收后读写任意寄存及可以开始接收
}

uint8_t sx127xRxData(lora_t *lora, uint8_t *buf, uint8_t *len)
{
	uint8_t u8_reciveLength;
	//Write127xReg(lora,REG_LR_DIOMAPPING1, (Read127xReg(lora,REG_LR_DIOMAPPING1) & RFLR_DIOMAPPING1_DIO0_MASK) | RFLR_DIOMAPPING1_DIO0_00 | RFLR_DIOMAPPING1_DIO1_00);
	if(lora->gpio_and_delay_cb(lora,LoRa_MSG_GPIO_EXIT_DIO0,10,0,0)==0)
	{
		Write127xReg(lora,REG_LR_IRQFLAGS, RFLR_IRQFLAGS_RXDONE); // 清除中断标志位
		u8_reciveLength = Read127xReg(lora,REG_LR_NBRXBYTES);
		if((Read127xReg(lora,REG_LR_IRQFLAGS)&RFLR_IRQFLAGS_PAYLOADCRCERROR)==RFLR_IRQFLAGS_PAYLOADCRCERROR)
		{
			Write127xReg(lora,REG_LR_IRQFLAGS, RFLR_IRQFLAGS_PAYLOADCRCERROR);
			return 1;
		}
		else
		{
			if (u8_reciveLength > *len)
			{
				u8_reciveLength = *len;
			}
			else
			{
				*len = u8_reciveLength;
			}
			SX127xReadFifo(lora,buf, u8_reciveLength);
			return 0;
		}
	}
	return 1;
}
/// @brief 接收数据（阻塞接收）
/// @param lora lora 设备句柄
/// @param buf 数据buf
/// @param len 数据长度
/// @param timeoutMs 超时时间
/// @return
uint8_t sx127xRx(lora_t *lora, uint8_t *buf, uint8_t *len, uint32_t timeoutMs)
{
	uint16_t time=0;
	uint8_t u8_reciveLength;

	SX127xSetOpMode(lora,LORA_OPMODE_STANDBY);
	Write127xReg(lora,REG_LR_FIFORXBASEADDR, 0);	   // 将接收buf的基地址指向0x00，测试整个fifo都可以用来发送数据
	Write127xReg(lora,REG_LR_FIFOADDRPTR, 0);	   // 将FIFO 读写指针执行0x00，此时向寄存器0x00读写数据指针会自增的将数据写入fifo
	Write127xReg(lora,REG_LR_SYMBTIMEOUTLSB, 0xFF); // 配置 0x1F rx 超时

	// 配置中断
	Write127xReg(lora,REG_LR_IRQFLAGSMASK, RFLR_IRQFLAGS_RXTIMEOUT |
										  // RFLR_IRQFLAGS_RXDONE |
										  RFLR_IRQFLAGS_PAYLOADCRCERROR |
										  RFLR_IRQFLAGS_VALIDHEADER |
										  RFLR_IRQFLAGS_TXDONE |
										  RFLR_IRQFLAGS_CADDONE |
										  RFLR_IRQFLAGS_FHSSCHANGEDCHANNEL |
										  RFLR_IRQFLAGS_CADDETECTED);
	// DIO0=RxDone 0x00, DIO2=RxTimeout 0x00
	Write127xReg(lora,REG_LR_DIOMAPPING1, (Read127xReg(lora,REG_LR_DIOMAPPING1) & RFLR_DIOMAPPING1_DIO0_MASK) | RFLR_DIOMAPPING1_DIO0_00 | RFLR_DIOMAPPING1_DIO1_00);
	SX127xSetOpMode(lora,LORA_OPMODE_RECEIVER); // 连续接收
	// SX127xSetOpMode( LORA_OPMODE_RECIVER_SINGLE );  //单次接收
	Read127xReg(lora,REG_LR_IRQFLAGS); // 设置接收后读写任意寄存及可以开始接收

	while (1)
	{
		if (1 == lora->gpio_and_delay_cb(lora,LoRa_MSG_GPIO_ReadDio0,0,0,0))
		{
			Write127xReg(lora,REG_LR_IRQFLAGS, RFLR_IRQFLAGS_RXDONE); // 清除中断标志位
			u8_reciveLength = Read127xReg(lora,REG_LR_NBRXBYTES);
			if (u8_reciveLength > *len)
			{
				u8_reciveLength = *len;
			}
			else
			{
				*len = u8_reciveLength;
			}
			SX127xReadFifo(lora,buf, u8_reciveLength);
			return 0;
		}
		if (1== lora->gpio_and_delay_cb(lora,LoRa_MSG_GPIO_ReadDio1,0,0,0))
		{
			Write127xReg(lora,REG_LR_IRQFLAGS, RFLR_IRQFLAGS_RXTIMEOUT); // 清除中断标志位
			return 1;
		}
		if(time>timeoutMs)
		{
			return 1;
		}
		time++;
		lora->gpio_and_delay_cb(lora,LoRa_MSG_DELAY_MILLI,1,0,0);
	}
}
/// @brief 非阻塞状态轮询函数
/// @param lora
/// @return
tRFProcessReturnCodes SX127xProcess(lora_t *lora)
{
	uint32_t currTick = 0;
	static uint32_t systickBak = 0;

	switch (loraStatus)
	{
	case RFLR_STATE_IDLE:
		return RF_IDLE;
	case RFLR_STATE_RX_INIT:
		SX127xSetOpMode(lora,LORA_OPMODE_STANDBY);
		Write127xReg(lora,REG_LR_FIFORXBASEADDR, 0);	   // 将接收buf的基地址指向0x00，测试整个fifo都可以用来发送数据
		Write127xReg(lora,REG_LR_FIFOADDRPTR, 0);	   // 将FIFO 读写指针执行0x00，此时向寄存器0x00读写数据指针会自增的将数据写入fifo
		Write127xReg(lora,REG_LR_SYMBTIMEOUTLSB, 0xFF); // 配置 0x1F rx 超时

		// 配置中断
		Write127xReg(lora,REG_LR_IRQFLAGSMASK, RFLR_IRQFLAGS_RXTIMEOUT |
											  // RFLR_IRQFLAGS_RXDONE |
											  RFLR_IRQFLAGS_PAYLOADCRCERROR |
											  RFLR_IRQFLAGS_VALIDHEADER |
											  RFLR_IRQFLAGS_TXDONE |
											  RFLR_IRQFLAGS_CADDONE |
											  RFLR_IRQFLAGS_FHSSCHANGEDCHANNEL |
											  RFLR_IRQFLAGS_CADDETECTED);
		// DIO0=RxDone 0x00, DIO2=RxTimeout 0x00
		Write127xReg(lora,REG_LR_DIOMAPPING1, (Read127xReg(lora,REG_LR_DIOMAPPING1) & RFLR_DIOMAPPING1_DIO0_MASK) | RFLR_DIOMAPPING1_DIO0_00 | RFLR_DIOMAPPING1_DIO1_00);
		SX127xSetOpMode(lora,LORA_OPMODE_RECEIVER); // 连续接收
		// SX127xSetOpMode( LORA_OPMODE_RECIVER_SINGLE ); //单次接收
		Read127xReg(lora,REG_LR_IRQFLAGS); // 设置接收后读写任意寄存器可以触发接收
		systickBak = lora->gpio_and_delay_cb(lora,LoRa_MSG_GetTick,0,0,0);//GET_TICK_COUNT();
		loraStatus = RFLR_STATE_RX_RUNNING;
		return RF_BUSY;
	case RFLR_STATE_RX_RUNNING:
		if (1 == lora->gpio_and_delay_cb(lora,LoRa_MSG_GPIO_ReadDio0,0,0,0))   //等待接收中断
		{
			Write127xReg(lora,REG_LR_IRQFLAGS, RFLR_IRQFLAGS_RXDONE); // 清除中断标志位
			loraStatus = RFLR_STATE_RX_DONE;
			return RF_BUSY;
		}
		if (1 == lora->gpio_and_delay_cb(lora,LoRa_MSG_GPIO_ReadDio1,0,0,0))  //接收超时中断
		{
			Write127xReg(lora,REG_LR_IRQFLAGS, RFLR_IRQFLAGS_RXTIMEOUT); // 清除中断标志位
			loraStatus = RFLR_STATE_RX_TIMEOUT;
			return RF_BUSY;
		}
		currTick = lora->gpio_and_delay_cb(lora,LoRa_MSG_GetTick,0,0,0);
		if (currTick >= systickBak)
		{
			if (currTick - systickBak > softTimeout)
			{
				loraStatus = RFLR_STATE_RX_TIMEOUT;
				return RF_BUSY;
			}
		}
		else
		{
			// currTick�����
			if (currTick + (~systickBak) > softTimeout)
			{
				loraStatus = RFLR_STATE_RX_TIMEOUT;
				return RF_BUSY;
			}
		}
		return RF_BUSY;
	case RFLR_STATE_RX_DONE:
		return RF_RX_DONE;
	case RFLR_STATE_RX_TIMEOUT:
		return RF_RX_TIMEOUT;
	case RFLR_STATE_TX_INIT:
		systickBak =lora->gpio_and_delay_cb(lora,LoRa_MSG_GetTick,0,0,0);;
		return RF_BUSY;
	case RFLR_STATE_TX_RUNNING:
		if (1 == lora->gpio_and_delay_cb(lora,LoRa_MSG_GPIO_ReadDio0,0,0,0))  //发送中断
		{
			Write127xReg(lora,REG_LR_IRQFLAGS, RFLR_IRQFLAGS_TXDONE); // 清除中断标志位
			loraStatus = RFLR_STATE_TX_DONE;
			return RF_BUSY;
		}
		if (1 == lora->gpio_and_delay_cb(lora,LoRa_MSG_GPIO_ReadDio0,0,0,0))   //发送中断
		{
			// 发送完成
			Write127xReg(lora,REG_LR_IRQFLAGS, RFLR_IRQFLAGS_TXDONE); // 清除中断标志位
			loraStatus = RFLR_STATE_TX_DONE;
			return RF_BUSY;
		}
		currTick = lora->gpio_and_delay_cb(lora,LoRa_MSG_GetTick,0,0,0);
		if (currTick >= systickBak)
		{
			if (currTick - systickBak > softTimeout)
			{
				loraStatus = RFLR_STATE_TX_TIMEOUT;
			}
		}
		else
		{
			// currTick溢出了
			if (currTick + (~systickBak) > softTimeout)
			{
				loraStatus = RFLR_STATE_TX_TIMEOUT;
			}
		}
		return RF_BUSY;
	case RFLR_STATE_TX_DONE:
		return RF_TX_DONE;
	case RFLR_STATE_TX_TIMEOUT:
		return RF_TX_TIMEOUT;
	case RFLR_STATE_CAD_INIT:
		SX127xSetOpMode(lora,LORA_OPMODE_STANDBY);
		// 配置中断
		Write127xReg(lora,REG_LR_IRQFLAGSMASK, RFLR_IRQFLAGS_RXTIMEOUT |
											  RFLR_IRQFLAGS_RXDONE |
											  RFLR_IRQFLAGS_PAYLOADCRCERROR |
											  RFLR_IRQFLAGS_VALIDHEADER |
											  RFLR_IRQFLAGS_TXDONE |
											  // RFLR_IRQFLAGS_CADDONE |
											  RFLR_IRQFLAGS_FHSSCHANGEDCHANNEL //|
					 // RFLR_IRQFLAGS_CADDETECTED
		);
		// RxDone                   RxTimeout                   FhssChangeChannel           CadDone
		Write127xReg(lora,REG_LR_DIOMAPPING1, RFLR_DIOMAPPING1_DIO0_10 | RFLR_DIOMAPPING1_DIO1_10 | RFLR_DIOMAPPING1_DIO2_00 | RFLR_DIOMAPPING1_DIO3_00);
		SX127xSetOpMode(lora,LORA_OPMODE_CAD); // 开启CAD 检测
		// Read127xReg(REG_LR_IRQFLAGS);//设置接收后读写任意寄存器可以触发接收
		systickBak = lora->gpio_and_delay_cb(lora,LoRa_MSG_GetTick,0,0,0);
		loraStatus = RFLR_STATE_CAD_RUNNING;
		return RF_BUSY;
	case RFLR_STATE_CAD_RUNNING:
		if (1 == lora->gpio_and_delay_cb(lora,LoRa_MSG_GPIO_ReadDio0,0,0,0))  //CAD 中断
		{
			// Clear Irq
			Write127xReg(lora,REG_LR_IRQFLAGS, RFLR_IRQFLAGS_CADDONE); 

			if (1 == lora->gpio_and_delay_cb(lora,LoRa_MSG_GPIO_ReadDio1,0,0,0))   //CAD 中断
			{	// CAD Detected interrupt
				// Clear Irq
				Write127xReg(lora,REG_LR_IRQFLAGS, RFLR_IRQFLAGS_CADDETECTED);
				// CAD detected, we have a LoRa preamble
				loraStatus = RFLR_STATE_CAD_DETECTED;
				return RF_BUSY;
			}
			else
			{
				// The device goes in Standby Mode automatically
				loraStatus = RFLR_STATE_CAD_EMPTY;
				return RF_BUSY;
			}
		} // end of if( 1 == SX1276ReadDio3() ){
		currTick = lora->gpio_and_delay_cb(lora,LoRa_MSG_GetTick,0,0,0);
		if (currTick >= systickBak)
		{
			if (currTick - systickBak > 100)
			{
				loraStatus = RFLR_STATE_CAD_TIMEOUT;
			}
		}
		else
		{
			// currTick溢出了
			if (currTick + (~systickBak) > 100)
			{
				loraStatus = RFLR_STATE_CAD_TIMEOUT;
			}
		}
		return RF_BUSY; // RF_CAD_DETECTED
	case RFLR_STATE_CAD_DETECTED:
		return RF_CAD_DETECTED;
	case RFLR_STATE_CAD_EMPTY:
		return RF_CAD_EMPTY;
	case RFLR_STATE_CAD_TIMEOUT:
		return RF_CAD_TIMEOUT;
	default:
		return RF_UNKNOW_STATUS;
	}

	// return RF_UNKNOW_STATUS;
}

/// @brief 非阻塞发送数据（需要配合 轮询SX127xProcess() 使用）
/// @param lora lora 设备句柄
/// @param buffer 需要发送的数据
/// @param size 发送长度
/// @param timeoutSystick 超时时间
void SX127xSetTxPacket(lora_t *lora, void *buffer, uint16_t size, uint32_t timeoutSystick)
{
	loraStatus = RFLR_STATE_TX_INIT;
	if (size > 255)
	{
		size = 255;
	}
	if (timeoutSystick > 0)
	{
		softTimeout = timeoutSystick;
	}
	else
	{
		softTimeout = DEFAUTL_TIMEOUT;
	}

	Write127xReg(lora,REG_LR_PAYLOADLENGTH, size); // 设置负载长度

	Write127xReg(lora,REG_LR_FIFOTXBASEADDR, 0); // 将发送buf的基地址指向0x00，测试整个fifo都可以用来发送数据
	Write127xReg(lora,REG_LR_FIFOADDRPTR, 0);	// 将FIFO 读写指针执行0x00，此时向寄存器0x00读写数据指针会自增的将数据写入fifo
	SX127xSetOpMode(lora,LORA_OPMODE_STANDBY);	// LORA_OPMODE_SLEEP模式不能写入fifo

	SX127xWriteFifo(lora,(uint8_t *)buffer, size); // 将要发送的数据写入fifo
	// 开启中断屏蔽位（只留下了 RFLR_IRQFLAGS_TXDONE 中断没有屏蔽掉,设置为发送模式后任意读写一个寄存器就会触发发送，这里写入这个开中断正好触发
	Write127xReg(lora,REG_LR_IRQFLAGSMASK, RFLR_IRQFLAGS_RXTIMEOUT |
										  RFLR_IRQFLAGS_RXDONE |
										  RFLR_IRQFLAGS_PAYLOADCRCERROR |
										  RFLR_IRQFLAGS_VALIDHEADER |
										  // RFLR_IRQFLAGS_TXDONE |
										  RFLR_IRQFLAGS_CADDONE |
										  RFLR_IRQFLAGS_FHSSCHANGEDCHANNEL |
										  RFLR_IRQFLAGS_CADDETECTED);
	Write127xReg(lora,REG_LR_DIOMAPPING1, (Read127xReg(lora,REG_LR_DIOMAPPING1) & RFLR_DIOMAPPING1_DIO0_MASK) | RFLR_DIOMAPPING1_DIO0_01); //
	SX127xProcess(lora);						  // 调用这个为了更新 systick
	SX127xSetOpMode(lora,LORA_OPMODE_TRANSMITTER); // 设置为发送模式
	Read127xReg(lora,REG_LR_IRQFLAGS);			  // 设置发送后读写任意寄存器可触发发送
	loraStatus = RFLR_STATE_TX_RUNNING;
}

/// @brief 非阻塞接收函数
/// @param lora
/// @param timeoutSystick
void Sx127xStartRx(lora_t *lora, uint32_t timeoutSystick)
{
	if (timeoutSystick > 0)
	{
		softTimeout = timeoutSystick;
	}
	else
	{
		softTimeout = DEFAUTL_TIMEOUT;
	}
	loraStatus = RFLR_STATE_RX_INIT;
}
/// @brief 读取fifo 中接收到的数据
/// @param lora
/// @param buffer
/// @param size
void Sx127xReadRxPackage(lora_t *lora, void *buffer, uint16_t *size)
{
	// 读取数据
	uint16_t tmpReciveLength;

	tmpReciveLength = Read127xReg(lora,REG_LR_NBRXBYTES);
	if (tmpReciveLength > *size)
	{
		tmpReciveLength = *size;
	}
	else
	{
		*size = tmpReciveLength;
	}
	SX127xReadFifo(lora,buffer, tmpReciveLength);
}

/// @brief 非阻塞 开启一次cad检测
/// @param lora
void Sx127xStartCADCheck(lora_t *lora)
{
	loraStatus = RFLR_STATE_CAD_INIT;
}
